// packageC/Myshaky/enroll/enroll.js
var app = getApp();
import util from "../../../utils/util.js";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    tap: 1,
    name: "",
    phone: "",
    email: "",
    firm: "",
    // showpaths: [],
    uploadUrl: app.getNetAddresss("upload.uploadPic"),
    swlist: [],
    // switch1:false,
    switch2: false,
    num: 1,
    arr: [],
    type: "enroll",
    formid: "",
    default_deduction:0,
    exchange_code_id:'',//兑换码日志id
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    this.setData({
      activity_id: options.id,
      exchange_code_id:options.exchange_code_id || '',
    });
    // this.getlist()
  },
  postForm(e) {
    console.log(e);
    // 更新
    let json = {
      form_id: this.data.form_id,
      form_data: e.detail,
    };
    if (this.data.count >= this.data.limit) {
      wx.showToast({
        title: "报名人数已超过限制",
        icon: "none",
        duration: 1000,
      });
      return;
    }
    let that = this;
    let urlStr = app.getNetAddresss("plugin.diyform.api.diy-form.save-diy-form-data");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          // if (that.data.type == 'enroll'){
          that.setData({
            "info.form_id": res.data.form_data_id,
          });
          that.toNew();
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {},
    });
  },
  toNew() {
    let that = this;
    let json = {
      form_data_id: this.data.info.form_id,
      activity_id: this.data.activity_id,
      form_id: this.data.form_id,
    };
    console.log(json);
    let urlStr = app.getNetAddresss("plugin.activity-apply.api.Activity.getDiyForm");
    app._getNetWork({
      url: urlStr,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          if(that.data.exchange_code_id){
            that.data.info.exchange_code_id = that.data.exchange_code_id;
          }
          that.notfree(that.data.info);
        } else {
          wx.showToast({
            title: res.msg,
            duration: 500,
            icon: "none",
          });
        }
      },
    });
  },
  notfree(info){
    let urlStr = app.getNetAddresss("plugin.activity-apply.api.create");
    app._postNetWork({
      url: urlStr,
      data: info,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          // that.selectComponent('.diyfromClass').setData({
          //   diydata:[],
          //   formList:[],
          //   form_data_id:that.data.info.form_id,
          //   payStatus:that.data.payStatus,
          //   applyStatus:that.data.applyStatus
          // })
          // that.selectComponent('.diyfromClass').getForm();
          wx.navigateTo({
            url: '/packageD/buy/orderPay/orderPay?order_id='+ res.data.order_ids+'&name=Myshaky',
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: '1000'
          });
        }
      },
      fail: function (res) {

      }
    });
  },
  onChange(val) {
    let btn = val.currentTarget.dataset.checked;
    let ind = val.currentTarget.dataset.ind;
    if (btn) {
      this.data.order_deductions[ind].checked = !btn;
      this.setData({
        order_deductions: this.data.order_deductions,
      });
    } else {
      this.data.order_deductions[ind].checked = !btn;
      this.setData({
        order_deductions: this.data.order_deductions,
      });
    }
    if (this.data.order_deductions[ind].checked == true) {
      if (this.data.arr.indexOf(val.currentTarget.dataset.name) <= -1) {
        this.data.arr.push(val.currentTarget.dataset.name);
      }
    }
    if (this.data.order_deductions[ind].checked == false) {
      if (this.data.arr.indexOf(val.currentTarget.dataset.name) > -1) {
        this.data.arr.splice(this.data.arr.indexOf(val.currentTarget.dataset.name), 1);
      }
    }
    
    let json = {
      address: JSON.stringify({}),
      dispatch_type_id: 0,
      goods_id: this.data.list.goods_id,
      total: this.data.num,
      option_id: "",
      orders: JSON.stringify([
        {
          deduction_ids: this.data.arr,
          pre_id: this.data.pre_id
        }
      ]),
      member_coupon_ids: "",
    };
    if (this.data.default_deduction != 0) {
      // 默认积分抵扣
      json.no_deduction_ids = this.data.default_deduction;
    }
    let urlStr = app.getNetAddresss("order.goods-buy");
    let that = this;
    app._getNetWork({
      url: urlStr,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          console.log(res);
          that.setData({
            total_price: res.data.total_price,
            pre_id: res.data.orders[0].pre_id,
            order_deductions: res.data.orders[0].order_deductions,
          });
          let info = {
            orders: JSON.stringify([
              {
                deduction_ids: that.data.arr,
                pre_id: that.data.pre_id,
              },
            ]),
            dispatch_type_id: 0,
            activity_id: that.data.activity_id,
            test_uid: wx.getStorageSync("uid"),
            lecturer_id: that.data.list.lecturer_id,
            calssify_id: that.data.list.calssify_id,
            goods: JSON.stringify([
              {
                goods_id: that.data.list.goods_id,
                total: that.num,
                option_id: 0,
              },
            ]),
            form_id: "",
          };
          that.setData({
            info: info,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1000,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  //获取优惠信息
  priceChange() {
    let urlStr = app.getNetAddresss("order.goods-buy");
    let that = this;
    let json = {
      address: JSON.stringify({}),
      dispatch_type_id: 0,
      goods_id: this.data.list.goods_id,
      total: this.data.num,
      option_id: "",
      orders: JSON.stringify([]),
      member_coupon_ids: "",
    };
    app._getNetWork({
      url: urlStr,
      data: json,
      success: (resdata)=> {
        var res = resdata.data;
        if (res.result == 1) {
          console.log(res);
          if (res.data.discount && res.data.discount.default_deduction && res.data.discount.default_deduction != 0) {
            // 获取第一次接口默认积分抵扣
            this.data.default_deduction = res.data.discount.default_deduction;
          }
          that.setData({
            total_price: res.data.total_price,
            pre_id: res.data.orders[0].pre_id,
            order_deductions: res.data.orders[0].order_deductions,
          });
          for (let val in that.data.order_deductions) {
            if (that.data.order_deductions[val].code == "point" && that.data.order_deductions[val].checked == true) {
              let arrs = [];
              arrs.push("point");
              that.setData({
                // nochecked: true,
                arr: arrs,
              });
            }
          }
          let info = {
            orders: JSON.stringify([
              {
                deduction_ids: that.data.arr,
                pre_id: that.data.pre_id,
              },
            ]),
            dispatch_type_id: 0,
            activity_id: that.data.activity_id,
            test_uid: wx.getStorageSync("uid"),
            lecturer_id: that.data.list.lecturer_id,
            calssify_id: that.data.list.calssify_id,
            goods: JSON.stringify([
              {
                goods_id: that.data.list.goods_id,
                total: that.data.num,
                option_id: 0,
              },
            ]),
            form_id: "",
          };
          that.setData({
            info: info,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1000,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.getlist()
    this.test();
    let pages = getCurrentPages(); //页面对象
    let prevpage = pages[pages.length - 2]; //上一个页面对象
    console.log(prevpage.route,pages); //上一个页面路由地址
    let path = prevpage.route;
    console.log(path, 'path');
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    // var value = wx.getStorageSync('yz_uid')
    // var mid = ''
    // if (value) {
    // 	mid = value
    // }
    return {
      path: "/packageC/Myshaky/enroll/enroll?id=" + this.data.activity_id,
    };
  },
  // 检测是否有填写过表单
  test() {
    let urlStr = app.getNetAddresss("plugin.activity-apply.api.Activity.getActivityEnrol");
    let that = this;
    app._getNetWork({
      url: urlStr,
      data: {
        activity_id: that.data.activity_id,
      },
      success: function (resdata) {
        var res = resdata.data;
        if(res.data&&res.data.enrol == 2){
          //添加权限
          app.tips(res.msg);
          wx.navigateBack()
          return false
        }
        if (res.result == 1) {
          console.log(res);

          that.setData({
            payStatus: res.data.enrol,
            applyStatus: res.data.status,
          });
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1000,
          });
          that.getlist();
        } else {
          that.setData({
            payStatus: 0,
          });
          that.getlist();
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  // 获取报名详情
  getlist() {
    let urlStr = app.getNetAddresss("plugin.activity-apply.api.Activity.getActivity");
    let that = this;
    app._getNetWork({
      url: urlStr,
      data: {
        activity_id: that.data.activity_id,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          console.log(res);
          res.data.start_time = util.formatTimeTwo(res.data.start_time, "Y/M/D h:m:s");
          res.data.end_time = util.formatTimeTwo(res.data.end_time, "Y/M/D h:m:s");

          that.setData({
            list: res.data,
            form_id: res.data.form_id,
            total_price:res.data.cash
          });
          let orderIds = that.data.list.has_many_pay_order.length > 0 ? that.data.list.has_many_pay_order[0].order_id : "";
          let fromDataId = !app._isTextEmpty(that.data.list.form_data_id) ? that.data.list.form_data_id.form_data_id : "";
          that.setData({
            orderId: orderIds,
            form_data_id: fromDataId,
          });
          console.log(Number(res.data.cash) > 0);
          if (Number(res.data.cash) > 0) {
            that.priceChange();
          } else {
            let infos = {
              dispatch_type_id: 0,
              activity_id: that.data.activity_id,
              test_uid: wx.getStorageSync("uid"),
              lecturer_id: that.data.list.lecturer_id,
              calssify_id: that.data.list.calssify_id,
              goods: JSON.stringify([
                {
                  goods_id: that.data.list.goods_id,
                  total: that.data.num,
                  option_id: 0,
                },
              ]),
              form_id: "",
            };
            that.setData({
              info: infos,
            });
          }
          // if (!app._isTextEmpty(res.data.goods_sale)) {
          //   that.setData({
          //     goods_sale: res.data.goods_sale
          //   })
          // } else {
          //   that.setData({
          //     goods_sale: false
          //   })
          // }
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
});
